package com.leapp.sk.viewdelegate.adapter.im

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.support.v4.content.ContextCompat
import android.text.TextUtils
import android.view.View
import android.widget.ImageView
import android.widget.ProgressBar
import android.widget.RelativeLayout
import android.widget.TextView
import cc.vv.lkbasecomponent.util.LKDateTimeUtil
import cc.vv.lkbasecomponent.util.LKStringUtil
import cc.vv.lkimcomponent.lkim.bean.LKIMMessage
import cc.vv.lkimcomponent.lkim.bean.body.LKIMVideoBody
import cc.vv.lkimcomponent.lkim.bean.venum.LKIMChatType
import cc.vv.lkimcomponent.lkim.bean.venum.LKIMStatus
import cc.vv.lklibrary.log.LogOperate
import com.bumptech.glide.Glide
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.bumptech.glide.request.RequestOptions
import com.example.baselibrary.db.dao.AccountDao
import com.example.baselibrary.db.table.AccountTable
import com.example.mvp.activity.VideoPlayerActivity
import com.example.mvp.delegate.BaseAdapterDelegate
import com.example.mvp.view.GlideCircleTransform
import com.example.mvp.view.GlideRoundTransform
import com.example.mvp.view.LKCircleImageView
import com.example.util.BCFinalist
import com.leapp.sk.R
import com.leapp.sk.ui.activity.im.MessageStateActivity
import com.leapp.sk.util.IMDialogUtil
import com.leapp.sk.util.SKTimeUtil
import com.example.util.finallist.*
import java.util.*

/**
 * 视频类型适配器视图托管类
 * @author  chaohaipeng  on 2018/7/20.
 */
class ChatVideoAdapterDelegate: BaseAdapterDelegate() {
    /**
     * 图片加载操作
     */
    var mRequestOptions: RequestOptions = RequestOptions()
    /**
     * 头像加载操作
     */
    var mHeadRequestOptions: RequestOptions = RequestOptions()

    val text: TextView? = null
    override fun getOptionsMenuId(): Int {
        return 0
    }

    override fun initWidget() {
    }

    override fun onDestroy() {
    }

    override fun initLayoutRes(): Int {
        return R.layout.sk_chat_video_message

    }
    /**
     * 设置收到消息View
     */
    fun setRecerveView(context: Context,lkimMessage: LKIMMessage,timeInterval:Int,position: Int){
        val v_scvdom_receive_root=getView<RelativeLayout>(R.id.v_scvdom_receive_root)
        val rl_scvdom_send_root=getView<RelativeLayout>(R.id.rl_scvdom_send_root)
        v_scvdom_receive_root.visibility=View.VISIBLE
        rl_scvdom_send_root.visibility=View.GONE
        setRecerveData(context,lkimMessage,timeInterval,position)
    }

    /**
     * 设置收到消息数据
     */
    private fun setRecerveData(context: Context,lkimMessage: LKIMMessage,timeInterval:Int,position: Int){
        val tv_scvdom_time = getView<TextView>(R.id.tv_scvdom_time)
        val iv_scvdom_receive_image = getView<ImageView>(R.id.iv_scvdom_receive_image)
        val lav_scvdom_receive_avatar = getView<LKCircleImageView>(R.id.lav_scvdom_receive_avatar)
        val tv_scvdom_receive_nick = getView<TextView>(R.id.tv_scvdom_receive_nick)
        val rl_scvdom_receive_content = getView<RelativeLayout>(R.id.rl_scvdom_receive_content)
        tv_scvdom_receive_nick.visibility=View.VISIBLE
        tv_scvdom_time.text = LKDateTimeUtil.formatDateTime(lkimMessage.msgTime, "")
        isShowTime(tv_scvdom_time, timeInterval, lkimMessage.msgTime, position)
       val headUrl= lkimMessage.getAttribute(IMExtKey.EXTKEY_AVATAR,"")
        val nick= lkimMessage.getAttribute(IMExtKey.EXTKEY_NICK,"")
        val accountTable = AccountDao.getInstance().queryById(lkimMessage.fromAccount)
        if (accountTable==null||!TextUtils.equals( accountTable.avatar,headUrl)||!TextUtils.equals( accountTable.nick,nick)){
            val accountTable = AccountTable()
            accountTable.avatar=headUrl
            accountTable.nick=nick
            accountTable.account=lkimMessage.fromAccount
            tv_scvdom_receive_nick.text=nick
            AccountDao.getInstance().createOrUpdate(accountTable)
            setHead(context,headUrl,lav_scvdom_receive_avatar)
        }else{
            val avatar = if (null == accountTable) "" else accountTable.avatar
            val nick = if (null == accountTable) LKStringUtil.getString(R.string.app_name) else accountTable.nick
            tv_scvdom_receive_nick.text=nick
            setHead(context,avatar,lav_scvdom_receive_avatar)
        }

        var lkImBody: LKIMVideoBody?=null
        try {
            lkImBody = lkimMessage.lkIMBody as LKIMVideoBody
        } catch (e: Exception) {
            lkImBody=null
        }
         if (lkImBody!=null){
             val remoteThumbUrl = lkImBody.remoteThumbUrl
             val remoteUrl = lkImBody.remoteUrl
             LogOperate.e("视频消息========"+remoteThumbUrl)
             initImage(context,iv_scvdom_receive_image,remoteThumbUrl,true)
             rl_scvdom_receive_content.setOnClickListener(object :View.OnClickListener{
                 override fun onClick(p0: View?) {

                     playerVideo(context,remoteUrl)
                 }
             })

             val activity=  context as Activity
             rl_scvdom_receive_content.setOnLongClickListener(View.OnLongClickListener {
                 IMDialogUtil.getInstance().longClickEvent(activity,lkimMessage)
                 true
             })
         }
    }

    /**
     * 初始化图片
     */
    fun initImage(context: Context,imageView:ImageView,imagePath: String,isSend:Boolean){
        /**
         * 图片圆角处理
         */
        var mGlideRoundTransform: GlideRoundTransform = GlideRoundTransform.getInstance(context)
        val tag = imageView.getTag(R.id.tag_video)
        if ( tag==null||!tag?.equals(imagePath)) {
            val mRequestManager = Glide.with(context)
            mRequestOptions.diskCacheStrategy(DiskCacheStrategy.NONE)
            mRequestOptions.skipMemoryCache(true)
            mRequestOptions.error(R.mipmap.icon_im_image_def)
            mRequestManager?.load(imagePath)
                    ?.thumbnail(0.2f)
                    ?.apply(mRequestOptions)
                    ?.into(imageView)
            imageView.setTag(R.id.tag_video,imagePath)
        }
    }



    /**
     * 设置头像和昵称
     */
    fun setHead(context: Context,headUrl:String?,headImage: LKCircleImageView){
        val tag = headImage.getTag(R.id.tag_head)
        if ( tag==null||!tag?.equals(headUrl)){
            val mRequestManager = Glide.with(context)
            mHeadRequestOptions?.diskCacheStrategy(DiskCacheStrategy.NONE)
            mHeadRequestOptions?.skipMemoryCache(true)
            mHeadRequestOptions?.error(R.mipmap.icon_defout_head)
            mHeadRequestOptions?.transforms(GlideCircleTransform(context))
            mRequestManager?.load(headUrl)
                    ?.thumbnail(0.2f)
                    ?.apply(mHeadRequestOptions)
                    ?.into(headImage)
            headImage.setTag(R.id.tag_head,headUrl)
        }
    }



    /**
     * 发送数据View
     */
    fun setSendDataView(context: Context, lkimMessage: LKIMMessage, timeInterval: Int, position: Int) {
        val v_scvdom_receive_root=getView<RelativeLayout>(R.id.v_scvdom_receive_root)
        val rl_scvdom_send_root = getView<RelativeLayout>(R.id.rl_scvdom_send_root)
        val tv_scvdom_send_msgStatus_def_yes = getView<TextView>(R.id.tv_scvdom_send_msgStatus_def_yes)
        val pb_scvdom_send_im_sending = getView<ProgressBar>(R.id.pb_scvdom_send_im_sending)
        val iv_scvdom_send_im_fail = getView<ImageView>(R.id.iv_scvdom_send_im_fail)
        rl_scvdom_send_root.visibility = View.VISIBLE
        v_scvdom_receive_root.visibility=View.GONE
        if (lkimMessage.lkimStatus == LKIMStatus.FAIL) {
            tv_scvdom_send_msgStatus_def_yes.visibility = View.INVISIBLE
            pb_scvdom_send_im_sending.visibility = View.INVISIBLE
            iv_scvdom_send_im_fail.visibility = View.VISIBLE
        } else if (lkimMessage.lkimStatus == LKIMStatus.SUCCESS) {
            setReadInfo(context,lkimMessage)
        } else if (lkimMessage.lkimStatus == LKIMStatus.INPROGRESS) {
            pb_scvdom_send_im_sending.visibility = View.INVISIBLE
            iv_scvdom_send_im_fail.visibility = View.INVISIBLE
            pb_scvdom_send_im_sending.visibility = View.VISIBLE
        }
        setSendData(context, lkimMessage, timeInterval, position)

    }
    /**
     * 设置已读信息
     */
    fun setReadInfo(context: Context,lkimMessage: LKIMMessage){
        val tv_scvdom_send_msgStatus_def_yes = getView<TextView>(R.id.tv_scvdom_send_msgStatus_def_yes)
        val pb_scvdom_send_im_sending = getView<ProgressBar>(R.id.pb_scvdom_send_im_sending)
        val iv_scvdom_send_im_fail = getView<ImageView>(R.id.iv_scvdom_send_im_fail)
        if (LKIMChatType.GroupChat==lkimMessage.lkimChatType){
            val groupMemerCount = Integer.valueOf(lkimMessage.getAttribute(IMExtKey.EXTKEY_GROUPMEMERCOUNT, SkKey.BTKEY_String_0))
            val readMembersCount = Integer.valueOf(lkimMessage.getAttribute(IMExtKey.EXTKEY_READMEMBERSCOUNT, SkKey.BTKEY_String_0))
            val unReadMemberCount = groupMemerCount - readMembersCount
            if (unReadMemberCount > 0) {
                tv_scvdom_send_msgStatus_def_yes.setTextColor(ContextCompat.getColor(context,R.color.color_4390E1))
                tv_scvdom_send_msgStatus_def_yes.text=String.format(Locale.CHINESE, LKStringUtil.getString(R.string.string_im_unread_portion), unReadMemberCount)
            } else {
                tv_scvdom_send_msgStatus_def_yes.text=context.resources.getString(R.string.string_im_read)
                tv_scvdom_send_msgStatus_def_yes.setTextColor(ContextCompat.getColor(context,R.color.color_C0C0C0))
            }
        }else{
            if (TextUtils.equals(lkimMessage.isAcked,"1")){
                tv_scvdom_send_msgStatus_def_yes.text=context.resources.getString(R.string.string_im_read)
                tv_scvdom_send_msgStatus_def_yes.setTextColor(ContextCompat.getColor(context,R.color.color_C0C0C0))
            }else{
                tv_scvdom_send_msgStatus_def_yes.text=context.resources.getString(R.string.string_im_unread)
                tv_scvdom_send_msgStatus_def_yes.setTextColor(ContextCompat.getColor(context,R.color.color_4390E1))
            }

        }
        tv_scvdom_send_msgStatus_def_yes.visibility=View.VISIBLE
        pb_scvdom_send_im_sending.visibility=View.INVISIBLE
        iv_scvdom_send_im_fail.visibility=View.INVISIBLE
    }
    /**
     * 初始化事件
     */
    fun initEvent(context: Activity, lkimMessage: LKIMMessage){
        val tv_scstm_send_msgStatus_def_yes=getView<TextView>(R.id.tv_scvdom_send_msgStatus_def_yes)
        val rl_scstm_send_content=getView<RelativeLayout>(R.id.rl_scvdom_send_content)
        tv_scstm_send_msgStatus_def_yes.setOnClickListener(object :View.OnClickListener{
            override fun onClick(p0: View?) {
                if (lkimMessage.lkimChatType == LKIMChatType.GroupChat) {
                    val unReadMemberIds = lkimMessage.getAttribute(IMExtKey.EXTKEY_UNREADMEMBERIDS, "")
                    val readMemberIds = lkimMessage.getAttribute(IMExtKey.EXTKEY_READMEMBERIDS, "")
                    val intent = Intent(context, MessageStateActivity::class.java)
                    intent.putExtra(READ_MESSAGE_IDS, readMemberIds)
                    intent.putExtra(UNREAD_MESSAGE_IDS, unReadMemberIds)
                    intent.putExtra(MSG_DATA,lkimMessage)
                    intent.putExtra(GROUP_ID, lkimMessage.toAccount)
                    context?.startActivity(intent)
                }

            }
        })
        rl_scstm_send_content.setOnLongClickListener(View.OnLongClickListener {
            IMDialogUtil.getInstance().longClickEvent(context,lkimMessage)
            true
        })

    }
    /**
     * 发送数据View
     */
    fun setSendData(context: Context, lkimMessage: LKIMMessage, timeInterval: Int, position: Int) {
        val tv_scvdom_time = getView<TextView>(R.id.tv_scvdom_time)
        val iv_scvdom_send_image = getView<ImageView>(R.id.iv_scvdom_send_image)
        val lav_scvdom_send_avatar = getView<LKCircleImageView>(R.id.lav_scvdom_send_avatar)
        val rl_scstm_send_content=getView<RelativeLayout>(R.id.rl_scvdom_send_content)
        tv_scvdom_time.text = LKDateTimeUtil.formatDateTime(lkimMessage.msgTime, "")
        isShowTime(tv_scvdom_time, timeInterval, lkimMessage.msgTime, position)
        val headUrl= lkimMessage.getAttribute(IMExtKey.EXTKEY_AVATAR,"")
        val nick= lkimMessage.getAttribute(IMExtKey.EXTKEY_NICK,"")
        val accountTable = AccountDao.getInstance().queryById(lkimMessage.fromAccount)
        if (accountTable==null){
            accountTable?.avatar=headUrl
            accountTable?.nick=nick
            accountTable?.account=lkimMessage.fromAccount
            setHead(context,headUrl,lav_scvdom_send_avatar)
        }else{
            val avatar = if (null == accountTable) "" else accountTable.avatar
            setHead(context,avatar,lav_scvdom_send_avatar)
        }

        var lkImBody: LKIMVideoBody?=null
        try {
            lkImBody = lkimMessage.lkIMBody as LKIMVideoBody
        } catch (e: Exception) {
            lkImBody=null
        }
        if (lkImBody!=null){
            val localUrl = lkImBody.localUrl
            initImage(context,iv_scvdom_send_image,localUrl,false)
            rl_scstm_send_content.setOnClickListener(object :View.OnClickListener{
                override fun onClick(p0: View?) {
                    playerVideo(context,localUrl)
                }
            })
            val activity=  context as Activity
            initEvent(activity,lkimMessage)
        }
    }

    /**
     * 播放视频
     */
    fun playerVideo(context: Context,videoPath:String){
    val intent=Intent(context, VideoPlayerActivity::class.java)
        intent.putExtra(BCFinalist.PATH_VIDEO_PATH,videoPath)
        context.startActivity(intent)


}
    /**
     * 间隔时间处理
     *
     * @param tv_time
     * @param timeInterval
     * @param time
     */
    private fun isShowTime(tv_time: TextView, timeInterval: Int, time: Long, position: Int) {
        if (timeInterval >= 5) {
            val dayOrHours = SKTimeUtil.getDayOrHours(time)
            tv_time.text = dayOrHours
            tv_time.visibility = View.VISIBLE
        } else {
            if (position == 0) {
                val dayOrHours = SKTimeUtil.getDayOrHours(time)
                tv_time.text = dayOrHours
                tv_time.visibility = View.VISIBLE
            } else {
                tv_time.visibility = View.GONE
            }

        }
    }
}